import {
  smartPhysicsBulkDeletes,
  smartPhysicsCreate,
  smartPhysicsIsFavorited,
  smartPhysicsPagination,
  smartPhysicsQueryAnswer,
  smartPhysicsUpdate,
} from '@/services/swagger/smartPhysics';
import { HeartFilled, HeartOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { FooterToolbar, ModalForm, PageContainer, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, message, Modal, Select } from 'antd';
import React, { useRef, useState } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

/**
 * @en-US Add
 * @zh-CN 添加
 * @param fields
 */
const handleAdd = async (question: string) => {
  const hide = message.loading('正在添加');
  try {
    await smartPhysicsCreate({ question: getPlainText(question) });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败, 请再次重试!');
    return false;
  }
};

const getPlainText = (html: string) => {
  return html.replace(/<[^>]*>/g, ''); // 去掉所有 HTML 标签
};

/**
 * @en-US Update  status
 * @zh-CN 修改状态
 * @param fields
 */
const handleStatus = async (id: number, status: number) => {
  const hide = message.loading('正在修改');
  try {
    await smartPhysicsUpdate({ id: id, status: status as API.PhysicsQuestionStatus });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败, 请再次重试!');
    return false;
  }
};

/**
 * @en-US Toggle favorite
 * @zh-CN 是否收藏
 * @param fields
 */
const handleToggleFavorite = async (fields: API.PhysicsQuestionOutputModel) => {
  const hide = message.loading('正在修改');
  try {
    await smartPhysicsIsFavorited({ id: fields.id as number });
    hide();
    if (fields.isFavorited) {
      message.success('取消收藏');
    } else {
      message.success('收藏成功');
    }
    return true;
  } catch (error) {
    hide();
    message.error('修改失败, 请再次重试!');
    return false;
  }
};

/**
 *  Delete
 * @zh-CN 删除
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.PhysicsQuestionOutputModel[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const ids = {
      ids: selectedRows.map((row) => row.id).join(','), // 示例 ID 列表
    } as API.SmartPhysicsBulkDeletesParams;

    await smartPhysicsBulkDeletes(ids);
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败, 请再次重试！');
    return false;
  }
};

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.QuestionOutputModel>();
  const [selectedRowsState, setSelectedRows] = useState<API.QuestionOutputModel[]>([]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalContent, setModalContent] = useState('');

  const [editorHtml, setEditorHtml] = React.useState('');

  const handleEditorChange = (html: string) => {
    console.log('html:', html);
    setEditorHtml(html);
  };

  /**
   * @en-US Fetch Answer
   * @zh-CN 获取答案
   * */
  const fetchAnswer = async (questionId: number) => {
    try {
      const answer = await smartPhysicsQueryAnswer({ id: questionId });
      setModalContent(answer.data as string);
      setIsModalVisible(true);
    } catch (error) {
      message.error('获取答案失败'); // 错误处理
    }
  };

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.QuestionOutputModel>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.updateForm.question.questionLabel"
          defaultMessage="Question"
        />
      ),
      dataIndex: 'question',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              fetchAnswer(entity.id as number);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.updateForm.isFavorited.favoritedLabel"
          defaultMessage="Is favorited"
        />
      ),
      dataIndex: 'isFavorited',
      valueType: 'select',
      valueEnum: {
        true: { text: '收藏' },
        false: { text: '未收藏' },
      },
      render: (text, entity) => {
        return (
          <a
            onClick={() => {
              handleToggleFavorite(entity);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
          >
            {entity.isFavorited ? <HeartFilled style={{ color: 'red' }} /> : <HeartOutlined />}
          </a>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Select {...rest} placeholder="请选择"></Select>;
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />,
      dataIndex: 'Status',
      valueType: 'select',
      valueEnum: {
        0: { text: '待查看' },
        1: { text: '已解决' },
        2: { text: '未解决' },
      },
      render: (text, entity) => {
        return (
          <Select
            value={Number(entity.status)} // 确保将text转为数字
            onChange={(value) => {
              handleStatus(entity.id as number, value as number);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
            placeholder="Select status" // 可以添加一个占位符
          >
            <Select.Option value={0}>
              <FormattedMessage
                id="pages.searchTable.status.pendingReview"
                defaultMessage="Pending Review"
              />
            </Select.Option>
            <Select.Option value={1}>
              <FormattedMessage id="pages.searchTable.status.resolved" defaultMessage="Resolved" />
            </Select.Option>
            <Select.Option value={2}>
              <FormattedMessage
                id="pages.searchTable.status.unresolved"
                defaultMessage="Unresolved"
              />
            </Select.Option>
          </Select>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Select {...rest} placeholder="请选择"></Select>;
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.created" defaultMessage="Created time" />,
      sorter: true,
      dataIndex: 'created',
      valueType: 'dateTime',
      search: false,
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.ChineseDictionaryOutputModel, API.SmartDictionariesPaginationParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.question.list',
          defaultMessage: 'Question list',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        request={smartPhysicsPagination}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: 'pages.searchTable.createForm.newQuestion',
          defaultMessage: 'New Question',
        })}
        width="600px"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(editorHtml);
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <div style={{ height: '300px' }}>
          <ReactQuill
            value={editorHtml}
            onChange={handleEditorChange}
            placeholder="请在这里输入你的问题......"
            style={{ height: '85%' }} // 使编辑器充满父容器
          />
        </div>
      </ModalForm>
      <Modal
        title={<FormattedMessage id="pages.searchTable.answer" defaultMessage="Answer" />}
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null} // 可以根据需要定义底部按钮
        width={1600} // 设置你想要的宽度
      >
        <div dangerouslySetInnerHTML={{ __html: modalContent }} />
      </Modal>
    </PageContainer>
  );
};

export default TableList;
